package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.glass.ui.Application;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.auth.params.AuthParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author：祝文龙
 * @ Date：2023-11-28-13:26
 * @ Version：1.0
 * @ Description：
 */
@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcMenuMapper xcMenuMapper;

    @Autowired
    ApplicationContext applicationContext;

    //    传入请求认证的参数就是AuthparamsDto
    //    参数s就是用户输入的username
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//      将传入的Json转换成AuthparamsDto对象
        AuthParamsDto authParamsDto = null;

        try {
            AuthParamsDto parse = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证的参数不合法!");
        }


//        认证类型
        String authType = authParamsDto.getAuthType();
//

//        根据认证的类型从spring容器中取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
//        调用统一的认证方法
        XcUserExt xcUserExt = authService.execute(authParamsDto);
        //封装xcUserExt用户信息为userdetails
//      权限

//        根据userdetails对象生成令牌
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);
        return userPrincipal;
    }

    /**
     * @param xcUser 用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     * @description 查询用户信息
     * @author Mr.M
     * @date 2022/9/29 12:19
     */
    public UserDetails getUserPrincipal(XcUserExt xcUser) {
        String password = xcUser.getPassword();
        String[] authorities = {"test"};
//        根据用户id查询用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        if (xcMenus.size()>0){
            List<String> permissions =new ArrayList<>();
            xcMenus.forEach(m -> {
//                拿到用户拥有的权限标识符
                permissions.add(m.getCode());
            });
//            将permissions转成数组
           authorities = permissions.toArray(new String[0]);
        }

        xcUser.setPassword(null);
        String userJSON = JSON.toJSONString(xcUser);
        UserDetails userDetails = User.withUsername(userJSON).password(password).authorities(authorities).build();
        return userDetails;
    }
}
